const Base = require("./base.js");
const cachePre = "CATE_";
const modelName = "cate";
module.exports = class extends Base {
  /**
   * 列表
   * @param name
   * @returns {Promise<any>}
   */
  async indexAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model(modelName);
    const result = {};
    result.errno = 0;
    result.data = await db.list(post);
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 删除
   * @param id
   * @returns {Promise<void>}
   */
  async delAction() {
    const post = this.post();
    const sT = Date.now();
    const db = this.model(modelName);
    let result = {};
    if (await db.hasChildren(post.id)) {
      result.errno = -1;
      result.errmsg = "请先删除子节点";
    } else
      try {
        await db.delete(post.id);
        result.errno = 0;
      } catch (e) {
        result.errno = -1;
        result.errmsg = e.toString();
      }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 添加
   * @returns {Promise<any>}
   */
  async addAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model(modelName);
    const result = {};
    try {
      result.data = await db.add(post);
      result.errno = 0;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 详情
   * @returns {Promise<any>}
   */
  async detailAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model(modelName);
    const result = {};
    try {
      result.errno = 0;
      let data;
      const cacheKey = `${cachePre}detail_${think.md5(JSON.stringify(post))}`;
      const cacheService = this.service("cache/key");
      post &&
        post.cache &&
        (await cacheService.set(cacheKey, JSON.stringify(post)));
      data = await this.cache(cacheKey);
      if (post && post.cache && data && data.id) result.cache = true;
      else {
        data = await db.detail(post);
        this.cache(cacheKey, data);
      }
      result.data = data;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }

  /**
   * 修改
   * @returns {Promise<any>}
   */
  async updateAction() {
    const sT = Date.now();
    const post = this.post();
    const db = this.model(modelName);
    const result = {};
    try {
      await db.where({ id: post.id }).update(post);
      result.errno = 0;
      result.data = post.id;
    } catch (e) {
      result.errno = -1;
      result.errmsg = e.toString();
    }
    result.time = Date.now() - sT;
    return this.json(this.format(result));
  }
};
